package com.shd.day03.stream;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.function.Supplier;
import java.util.stream.Stream;

/**
 * @author S5343
 * @date 2018年7月22日下午8:57:51
 */
public class CreateStream {

	public static void main(String[] args) {
		Stream<String> stream = createStreamFromCollection();
		stream.forEach(System.out::println);

		createStreamFromValues().forEach(System.out::println);

		createStreamFromArrays().forEach(System.out::println);

		createStreamFromFile();

		createStreamFromIterator().forEach(System.out::println);

		createStreamFromGenerate().forEach(System.out::println);

		createObjFromGenerate().forEach(System.out::println);
	}

	private static Stream<String> createStreamFromCollection() {
		List<String> list = Arrays.asList("hello", "alax", "shd", "wolrd");
		return list.stream();
	}

	private static Stream<String> createStreamFromValues() {
		return Stream.of("hello", "world");
	}

	private static Stream<String> createStreamFromArrays() {
		return Arrays.stream(new String[] { "a", "b", "c" });
	}

	private static Stream<String> createStreamFromFile() {
		Path path = Paths.get("E:\\1.txt");
		try (Stream<String> lines = Files.lines(path)) {
			lines.forEach(System.out::println);
			return lines;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	private static Stream<Integer> createStreamFromIterator() {
		Stream<Integer> stream = Stream.iterate(0, n -> n + 2).limit(10);
		return stream;
	}

	private static Stream<Double> createStreamFromGenerate() {
		return Stream.generate(Math::random).limit(10);
	}

	private static Stream<Obj> createObjFromGenerate() {
		return Stream.generate(new ObjSupplier()).limit(10);
	}

	static class ObjSupplier implements Supplier<Obj> {

		private int index = 0;
		private Random random = new Random(System.currentTimeMillis());

		@Override
		public Obj get() {
			index = random.nextInt(100);
			return new Obj(index, "Name->" + index);
		}

	}

	static class Obj {
		private int id;
		private String name;

		/**
		 * @param id
		 * @param name
		 */
		public Obj(int id, String name) {
			super();
			this.id = id;
			this.name = name;
		}

		public int getId() {
			return id;
		}

		public void setId(int id) {
			this.id = id;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		@Override
		public String toString() {
			return "Obj [id=" + id + ", name=" + name + "]";
		}

	}

}
